package com.kusen.text;

import org.springframework.util.StringUtils;
import sun.security.provider.MD5;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 接入喜马拉雅生成的sig 签名数据
 */
public class StringTest {
    public static void main(String[] args) {
        StringTest stringTest = new StringTest();
        stringTest.getPaidAlbumByIds("40412609");
    }


    public void getPaidAlbumByIds(String ids) {
        if (false) {

        } else {
            //https://api.ximalaya.com/open_pay/batch_get_paid_albums?ids=40412609&sig=de319e614607d04dcb7b241e4ed2e693
            Map<String, String> result = new HashMap<String, String>();
            String app_key = XimalayaConfig.app_key;
            String nonce = getRandomString(32);
            String timestamp = String.valueOf(new Date().getTime());
            result.put("app_key", app_key);
            result.put("client_os_type", "4");
            result.put("nonce", nonce);
            //result.put("timestamp",timestamp);
            //result.put("server_api_version","1.0.0");
            result.put("ids", ids);//5b63fc9be55a8b0beba321c086b0bf5b
            String keyHash = XimalayaConfig.app_secret + XimalayaConfig.serverAuthenticateStaticKey;
            try {
                String sig = SignatureDemo.caculateSignature(result, keyHash);
                result.put("sig", sig);
                //拼接访问路径
                StringBuffer sb = new StringBuffer(XimalayaConfig.url).append(XimalayaConfig.album_tracks_rul).append("?");
                //发送http请求
                System.out.println(getCompleteUrl(sb, result));
                String data = SignatureDemo.doGet(getCompleteUrl(sb, result));
                if (!StringUtils.isEmpty(data)) {
                    System.out.println(data);
                    //  sendMessage(State.Success, "获取数据成功",data);
                } else {
                    //sendMessage(State.NoData, "无数据",data);
                }
            } catch (Exception e) {

            }


        }
    }

    private String getCompleteUrl(StringBuffer sb, Map<String, String> result) {
        for (Map.Entry<String, String> entry : result.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static String getRandomString(int length) {
        //1. 定义一个字符串（A-Z，a-z，0-9）即62个数字字母；
        String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        //2. 由Random生成随机数
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        //3. 长度为几就循环几次
        for (int i = 0; i < length; ++i) {
            //从62个的数字或字母中选择
            int number = random.nextInt(62);
            //将产生的数字通过length次承载到sb中
            sb.append(str.charAt(number));
        }
        //将承载的字符转换成字符串

        return sb.toString().toLowerCase();
    }

    public static String getSig(int page, int count) {
        String res = "";
        // StringBuffer sb = new StringBuffer("app_key=7a3ccf87ef94dba229bb78814ebd4a54&");
        StringBuffer sb = new StringBuffer("app_key=99b37417e1185eda1378600593b45c40&");
        sb.append("client_os_type=4&");
        sb.append("nonce=plqtl14smcitwd2pe1mbyr2nnf3vtjiy&");
        long time = new Date().getTime();
        sb.append("timestamp=" + time + "&");
        sb.append("album_id=40412609&");
        sb.append("sort=asc&");
        sb.append("contains_track_rich_intro=true&");
        sb.append("page=" + page + "&");
        sb.append("count=" + count + "&");
        try {
            res = new sun.misc.BASE64Encoder().encode(sb.toString().getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return res;
    }


    public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        byte[] data = encryptKey.getBytes();
        //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
        //生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance("HmacSHA1");
        //用给定密钥初始化 Mac 对象
        mac.init(secretKey);

        byte[] text = encryptText.getBytes();
        //完成 Mac 操作
        return mac.doFinal(text);
    }

    // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    // 返回形式为数字跟字符串
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    // 全局数组
    private final static String[] strDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "j", "?", "~"};

    public static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 254 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};


    // 2进制转16进制
    public static String bytes2Hex(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        int temp;
        try {
            for (int i = 0; i < bytes.length; i++) {
                temp = bytes[i];
                if (temp < 0) {
                    temp += 256;
                }
                if (temp < 16) {
                    result.append("0");
                }
                result.append(Integer.toHexString(temp));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }


    public static String MD5Encode(byte[] bytes) {
        String resultString = null;
        try {
            resultString = new String(bytes);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString
                    .getBytes()));
        } catch (Exception ex) {

        }
        return resultString;
    }
}